package com.anysoft.visitdd.example;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Set;

public class ProjectSecurityCommon {
    public static final String ALG_RSA_FOR_ANDROID = "RSA/ECB/PKCS1Padding";
    public static final String ALG_RSA = "RSA";
    public static final int RSA_DEC_STEP = 128;
    public static final int RSA_ENC_STEP = 117;

    static byte[] rsaDecrypt(
            Cipher cipher, byte[] source
    ) throws IOException, BadPaddingException, IllegalBlockSizeException {
        try (var baos = new ByteArrayOutputStream()) {
            for (int i = 0; i < source.length; i += RSA_DEC_STEP) {
                var stopIndex = Math.min(source.length, i + RSA_DEC_STEP);
                var message_e_sub_ba = Arrays.copyOfRange(source, i, stopIndex);
                var message_d_sub_ba = cipher.doFinal(message_e_sub_ba);
                baos.write(message_d_sub_ba);
            }
            return baos.toByteArray();
        }
    }

    static byte[] rsaEncrypt(
            Cipher cipher, byte[] source
    ) throws IOException, BadPaddingException, IllegalBlockSizeException {
        try (var baos = new ByteArrayOutputStream()) {
            for (int i = 0; i < source.length; i += RSA_ENC_STEP) {
                var stopIndex = Math.min(source.length, i + RSA_ENC_STEP);
                var subSource = Arrays.copyOfRange(source, i, stopIndex);
                var subTarget = cipher.doFinal(subSource);
                baos.write(subTarget);
            }
            return baos.toByteArray();
        }
    }

    public static String hash(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes());
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
